//
//  JokesViewController.m
//  Otaku
//
//  Created by lanou3g on 16/5/5.
//  Copyright © 2016年 Liuwx. All rights reserved.
//

#import "JokesViewController.h"
#import "JokeModel.h"
#import "JokeCell.h"
#import "Tool.h"
#import "DetaillsTableViewController.h"



@interface JokesViewController ()<UITableViewDataSource,UITableViewDelegate,UMSocialUIDelegate>
@property (nonatomic, strong) NSMutableArray *jokeArray;

@property (nonatomic, strong) LORefresh *headerRefresh;

@property (nonatomic, strong) UITableView *myTableview;

@property (nonatomic, strong) NSString *currentSkinModel;


@property (nonatomic, strong) JokeModel *shareModel;

@end

@implementation JokesViewController




- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSkinModel) name:SkinModelDidChangedNotification object:nil];
    [self updateSkinModel];
    
}

- (void)updateSkinModel {
    
   self.currentSkinModel = [[NSUserDefaults standardUserDefaults] stringForKey:CurrentSkinModelKey];
    
    if ([self.currentSkinModel isEqualToString:NightSkinModelValue]) {
        self.view.backgroundColor = [UIColor blackColor];
//        self.nameTextField.backgroundColor = [UIColor darkGrayColor];
//        self.SignatureTextView.backgroundColor = [UIColor darkGrayColor];
//        self.nameTextField.textColor  = [UIColor grayColor];
//        self.SignatureTextView.textColor = [UIColor grayColor];
        
    }else {
        self.view.backgroundColor = [UIColor colorWithRed:250.0/255.0 green:250.0/255.0  blue:250.0/255.0  alpha:1.0];
//        self.nameTextField.backgroundColor = [UIColor whiteColor];
//        self.SignatureTextView.backgroundColor = [UIColor whiteColor];
//        self.nameTextField.textColor = [UIColor blackColor];
//        self.SignatureTextView.textColor = [UIColor blackColor];
        
    }
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.myTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //数据请求
    [self loadDataFromServerType:self.type Start:@"0"];
    
    self.myTableview.delegate = self;
    self.myTableview.dataSource = self;
    [self.view addSubview:self.myTableview];
    
    //注册cell
    [self.myTableview registerNib:[UINib nibWithNibName:@"JokeCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    
    //下拉刷新
    __weak typeof(self) weakSelf = self;
    [self.myTableview addRefreshWithRefreshViewType:LORefreshViewTypeHeaderDefault refreshingBlock:^{
        [weakSelf.jokeArray removeAllObjects];
        [weakSelf.myTableview reloadData];
        [weakSelf loadDataFromServerType:weakSelf.type Start:@"0"];
    }];
    self.headerRefresh = [self.myTableview defaultHeader];
    

    
}

- (NSMutableArray *)jokeArray {
    if (!_jokeArray) {
        _jokeArray = [NSMutableArray new];
    }
    return _jokeArray;
}

- (UITableView *)myTableview {
    if (!_myTableview) {
        _myTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, FUll_VIEW_WIDTH, FUll_CONTENT_HEIGHT - PageBtn) style:UITableViewStylePlain];
    }
    return _myTableview;
}
//解析数据
-(void)loadDataFromServerType:(NSString *)type Start:(NSString *)start {
    [LWXNetWorkRequestManager requestURL:[NSURL URLWithString:@"http://lf.snssdk.com/neihan/stream/mix/v1/?mpic=1&webp=1&essence=1&content_type=-102&message_cursor=-1&bd_longitude=116.343215&bd_latitude=40.030637&bd_city=%E5%8C%97%E4%BA%AC%E5%B8%82&am_longitude=116.343525&am_latitude=40.030702&am_city=%E5%8C%97%E4%BA%AC%E5%B8%82&am_loc_time=1462280938812&count=30&min_time=1462275228&screen_width=1536&iid=3925604177&device_id=3380358324&ac=wifi&channel=meizu&aid=7&app_name=joke_essay&version_code=500&version_name=5.0.0&device_platform=android&ssmix=a&device_type=MX4+Pro&os_api=19&os_version=4.4.4&uuid=865863029385957&openudid=8bb7d74390874c25&manifest_version_code=500"] Method:LWX_GET Params:nil Result:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        if (data) {
            NSMutableDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            NSDictionary *dataDict = jsonData[@"data"];
            
            for (NSDictionary *itemDict in dataDict[@"data"]) {
                JokeModel *model = [JokeModel new];
                [model setValuesForKeysWithDictionary: itemDict];
                if (model.text.length > 0) {
                    [self.jokeArray addObject:model];
                }
                
                
            }
            
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.myTableview reloadData];
                [[self.myTableview defaultHeader]endRefreshing];
            });
        }
    }];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.jokeArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    JokeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath] ;
    if ([self.currentSkinModel isEqualToString:DaySkinModelValue]) {//日间模式
        [cell updateToDaySkinMode];
        } else {
        [cell updateToNightSkinMode];
        }
    cell.model = self.jokeArray[indexPath.row];
    self.shareModel = self.jokeArray[indexPath.row];
    [cell.shareButton addTarget:self action:@selector(shareBtnAction:) forControlEvents:UIControlEventTouchDownRepeat];
    
    
    return cell;
}


//分享点击事件
- (void)shareBtnAction:(UIButton *)share {
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"572c6a8ce0f55ac72d000352"
                                      shareText:@"分享的文字"
                                     shareImage:[UIImage imageNamed:@"icon"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,nil]
                                       delegate:self];
    [UMSocialData defaultData].extConfig.title = self.shareModel.text;
    [UMSocialData defaultData].shareText = [NSString stringWithFormat:@"%@+%@",self.shareModel.text,self.shareModel.share_url];

}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JokeModel *model = self.jokeArray[indexPath.row];
    
    CGFloat labeleHeight = [Tool labelHeightWithText:model.text font:[UIFont systemFontOfSize:17]];
    
    return labeleHeight + 180;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    DetaillsTableViewController *deVC = [[DetaillsTableViewController alloc]init];
    deVC.array = self.jokeArray;
    deVC.indexPath = indexPath.row;
    deVC.jokemodel = self.jokeArray[indexPath.row];
    [self.navigationController pushViewController:deVC animated:YES];

    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
